import { getCurrentTimeParam } from "./globalTimeFilter.js";
import { API_CONFIG } from "./config.js"; // 导入全局API配置

document.addEventListener("DOMContentLoaded", function () {
  // 获取或创建图表容器
  const guapaiElement = document.getElementById("guapai");
  if (!guapaiElement) {
    console.error("无法找到图表容器元素 #guapai");
    return;
  }

  // 创建新的图表结构
  guapaiElement.innerHTML = `
        <div class="consultation-total-container">
            <div class="chart-controls">
                <div class="time-filters">
                    <div class="time-filter active" data-period="day"></div>
                    <div class="time-filter" data-period="month"></div>
                    <div class="time-filter" data-period="year"></div>
                </div>
                <div class="chart-legend">
                    <div class="legend-item">
                        <div class="legend-color" style="background:#1d6fa0"></div>
                        <span>电话咨询</span>
                    </div>
                    <div class="legend-item">
                        <div class="legend-color" style="background:#24bbec"></div>
                        <span>文字咨询</span>
                    </div>
                    <div class="legend-item">
                        <div class="legend-color" style="background:#ffc640"></div>
                        <span>智能客服</span>
                    </div>
                </div>
            </div>
            <div class="chart-container" style="flex:1;position: relative">
                <div id="consultation-chart" style="width: 100%;height: 100%"></div>
            </div>

        </div>
    `;

  // 添加样式
  const style = document.createElement("style");
  style.innerHTML = `
        /* 新增: 使用flex布局确保图表容器正确伸缩 */
        .consultation-total-container {
            display: flex;
            flex-direction: column;
            height: 100%;
            width: 100%;
            border-radius: 8px;
            border: 1px solid rgba(36, 187, 236, 0.2);
        }
        
        .chart-controls {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            flex-shrink: 0; /* 防止被压缩 */
        }
        
        /* 新增: 图表容器使用剩余空间 */
        .chart-container {
            flex: 1;
            min-height: 0; /* 修复flex容器中的溢出问题 */
            position: relative;
            min-height: 300px;
            height: 100%;
            
        }
        
        #consultation-chart {
            width: 100%;
            height: 100%;
        }
        
        /* 其他样式保持不变... */
        .time-filters {
            display: flex;
            gap: 10px;
        }
        
        .time-filter {
            padding: 5px 12px;
            background: rgba(10, 58, 124, 0.5);
            border: 1px solid rgba(29, 111, 160, 0.3);
            color: #a2d3e8;
            border-radius: 4px;
            cursor: pointer;
            font-size: 1.4rem;
        }
        
        .time-filter.active {
            background: rgba(36, 187, 236, 0.2);
            color: #24bbec;
            font-weight: bold;
        }
        
        .chart-legend {
            display: flex;
            gap: 15px;
        }
        
        .legend-item {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 1.4rem;
        }
        .legend-item span{
            color: #fff;
        }
        
        .legend-color {
            width: 12px;
            height: 12px;
            border-radius: 3px;
        }
        
        .data-overview {
            display: flex;
            justify-content: space-between;
            margin-top: 15px;
            background: rgba(10, 58, 124, 0.4);
            padding: 12px 15px;
            border-radius: 6px;
            flex-shrink: 0; /* 防止被压缩 */
        }
        
        .data-item {
            text-align: center;
        }
        
        .data-value {
            font-size: 1.4rem;
            font-weight: bold;
            margin-bottom: 5px;
            background: linear-gradient(to right, #fff, #24bbec);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }
        
        .data-label {
            color: #a2d3e8;
            font-size: 1.4rem;
        }
        
        .data-update {
            text-align: right;
            margin-top: 8px;
            font-size: 1.4rem;
            color: #a2d3e8;
        }
    `;
  document.head.appendChild(style);

  // 初始化图表
  initConsultationChart();
});

function initConsultationChart() {
  const chartDom = document.getElementById("consultation-chart");
  if (!chartDom) {
    console.error("无法找到图表容器元素 #consultation-chart");
    return;
  }

  const chart = echarts.init(chartDom);
  let currentData = {
    phone: [],
    text: [],
    ai: [],
  };
  let currentCategories = [];

  document.addEventListener("timePeriodChanged", async function(event) {
    const periodType = event.detail.period;
    const data = await fetchData(periodType);
    updateChart(chart, data, periodType);
  });


  // 处理API数据
  function processData(result, periodType) {
    const groupedData = {};

    // 1. 按日期时间分组
    result.forEach(item => {
      let dateKey;

      // 根据选择的时间范围类型确定分组键
      switch(periodType) {
        case "day":
          // 对于日视图，按小时分组
          dateKey = new Date(item.calculate_time).toISOString().slice(11, 13) + "时";
          break;
        case "month":
          // 对于月视图，按日分组
          dateKey = new Date(item.calculate_time).getDate() + "日";
          break;
        case "year":
        default:
          // 对于年视图，按月分组
          const month = new Date(item.calculate_time).getMonth() + 1;
          dateKey = month + "月";
          break;
      }

      if (!groupedData[dateKey]) {
        groupedData[dateKey] = {
          count: 0
        };
      }

      groupedData[dateKey].count += parseInt(item.all_consult_count) || 0;
    });

    // 2. 创建有序的时间序列
    let sortedDates;

    switch(periodType) {
      case "day":
        // 日视图：0-23小时
        sortedDates = Array.from({length: 24}, (_, i) => `${i}时`);
        break;
      case "month":
        // 月视图：1-31日
        sortedDates = Array.from({length: 31}, (_, i) => `${i + 1}日`);
        break;
      case "year":
      default:
        // 年视图：1-12月
        sortedDates = Array.from({length: 12}, (_, i) => `${i + 1}月`);
        break;
    }

    // 3. 确保所有时间点都有数据
    sortedDates.forEach(date => {
      if (!groupedData[date]) {
        groupedData[date] = { count: 0 };
      }
    });

    // 4. 按排序规则组织最终数据
    const categories = [];
    const phoneData = [];
    const textData = [];
    const aiData = [];

    sortedDates.forEach(date => {
      if (groupedData[date]) {
        categories.push(date);

        const total = groupedData[date].count;
        phoneData.push(Math.round(total * 0.6));
        textData.push(Math.round(total * 0.3));
        aiData.push(Math.round(total * 0.1));
      }
    });

    return {
      categories,
      data: { phone: phoneData, text: textData, ai: aiData }
    };
  }

  // 获取数据
  async function fetchData(periodType) {
    const id = "0e613sdfwca044c1b0dbb1dessdgsegc";
    const type = "1";
    const time = getCurrentTimeParam();

    const params = new URLSearchParams({ id, time, type });
    const url = `${API_CONFIG.BASE_URL}/api/metrics/${id}/single-metrics-value?${params}`;

    try {
      const response = await axios.get(url);
      if (response.data?.code === "00000") {
        return processData(response.data.data, periodType);
      }
      throw new Error(response.data?.msg || "API请求失败");
    } catch (error) {
      console.error("获取咨询数据失败:", error);
      // 返回空数据
      return {
        categories: [],
        data: { phone: [], text: [], ai: [] }
      };
    }
  }

  // 更新图表
  function updateChart(chart, data, periodType) {
    // 根据不同的时间范围设置不同的坐标轴标签
    let nameMap = {};

    switch(periodType) {
      case "day":
        nameMap = {
          hour: "时",
          month: "月",
          year: "年"
        };
        break;
      case "month":
        nameMap = {
          hour: "时",
          month: "月",
          year: "年"
        };
        break;
      case "year":
      default:
        nameMap = {
          hour: "时",
          month: "月",
          year: "年"
        };
        break;
    }
    const option = {
      tooltip: {
        trigger: "axis",
        axisPointer: { type: "shadow" },
        backgroundColor: "rgba(6, 33, 68, 0.9)",
        borderColor: "#24bbec",
        textStyle: {
          color: "#fff",
        },
        formatter: function (params) {
          const phone = params[0];
          const text = params[1];
          const ai = params[2];

          const total = phone.value + text.value + ai.value;
          const phonePercent = Math.round((phone.value / total) * 100) || 0;
          const textPercent = Math.round((text.value / total) * 100) || 0;
          const aiPercent = Math.round((ai.value / total) * 100) || 0;

          return `${phone.name}<br/>
                    ${phone.marker}${phone.seriesName}: <span style="color:#1d6fa0;font-weight:bold">${phone.value} (${phonePercent}%)</span><br/>
                    ${text.marker}${text.seriesName}: <span style="color:#24bbec;font-weight:bold">${text.value} (${textPercent}%)</span><br/>
                    ${ai.marker}${ai.seriesName}: <span style="color:#ffc640;font-weight:bold">${ai.value} (${aiPercent}%)</span><br/>
                    <b>总量: ${total}</b>`;
        },
      },
      grid: {
        left: "3%",
        right: "4%",
        top: "8%",
        bottom: "15%",
        containLabel: true,
      },
      xAxis: {
        type: "category",
        data: data.categories,
        axisLine: { lineStyle: { color: "#5d96c1" } },
        axisLabel: {
          color: "#a2d3e8",
          fontSize: 12,
          // 自动处理不同时间范围的格式
          formatter: function(value) {
            if (periodType === "day" && value.endsWith("时")) {
              return value.replace("时", ":00");
            }
            return value;
          }
        }
      },
      yAxis: {
        type: "value",
        name: "咨询量",
        nameTextStyle: {
          color: "#a2d3e8",
          fontSize: 12,
          // 根据时间范围添加不同的单位
          rich: {
            unit: {
              color: "#a2d3e8",
              fontSize: 10
            }
          }
        },
        axisLine: { lineStyle: { color: "#5d96c1" } },
        splitLine: { lineStyle: { color: "rgba(93, 150, 193, 0.2)" } },
        axisLabel: { color: "#a2d3e8", fontSize: 12 }
      },
      series: [
        {
          name: "电话咨询",
          type: "bar",
          stack: "total",
          data: data.data.phone,
          itemStyle: { color: "#1d6fa0" }
        },
        {
          name: "文字咨询",
          type: "bar",
          stack: "total",
          data: data.data.text,
          itemStyle: { color: "#24bbec" }
        },
        {
          name: "智能客服",
          type: "bar",
          stack: "total",
          data: data.data.ai,
          itemStyle: { color: "#ffc640" }
        }
      ],
      dataZoom: [{ type: "inside" }]
    };

    chart.setOption(option);
    chart.resize(); // 确保正确渲染
  }

  // 时间筛选功能
  document.querySelectorAll(".time-filter").forEach(btn => {
    btn.addEventListener("click", function() {
      document.querySelectorAll(".time-filter").forEach(b => b.classList.remove("active"));
      this.classList.add("active");

      const periodType = this.dataset.period;
      document.dispatchEvent(new CustomEvent("timePeriodChanged", {
        detail: { period: periodType }
      }));
    });
  });

  // 初始加载 - 默认触发日视图
  const activeBtn = document.querySelector(".time-filter.active");
  if (activeBtn) {
    document.dispatchEvent(new CustomEvent("timePeriodChanged", {
      detail: { period: activeBtn.dataset.period }
    }));
  }

  // 响应窗口调整
  window.addEventListener("resize", () => chart.resize());

  // 定时更新
  setInterval(async () => {
    const activeBtn = document.querySelector(".time-filter.active");
    if (activeBtn) {
      const data = await fetchData(activeBtn.dataset.period);
      updateChart(chart, data, activeBtn.dataset.period);
    }
  }, 10000000);
}
